from django.shortcuts import render
from django.views import View
from django import http
from django.core.cache import cache


from .models import Areas
from meiduo_mall.utils.response_code import RETCODE


class AreasView(View):
    """省市区视图"""

    def get(self, request):
        # 前端请求 /areas/?areas_id = xx,通过判断area_id来返回
        area_id = request.GET.get('area_id')
        if area_id is None:
            # 存到redis,减少访问mysql次数，提高性能
            province_list = cache.get('province_list')
            if province_list is None:
                # 返回省部分
                province_qs = Areas.objects.filter(parent=None)
                # 前端需要接收json格式，将查询集转变为[{}{}]
                province_list = []  # 定义一个省的空列表province_list
                # 遍历查询集变为字典形式加到列表中
                for province_model in province_qs:
                    province_model = {
                        # 把id传过去
                        'id': province_model.id,
                        'name': province_model.name
                    }
                    province_list.append(province_model)
                cache.set('province_list', province_list, 3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})
        # area_id有值表示请求市或者区

        data_dict = cache.get('sub_area' + area_id)
        if data_dict is None:
            # 获取当前查询的行政区
            parent_model = Areas.objects.get(id=area_id)
            # 一查多得到下级行政区查询集 book.hero_set.all() = book.subs.all()
            sub_qs = parent_model.subs.all()
            sub_qs_list = []
            for sub_model in sub_qs:
                sub_model = {
                    'id':sub_model.id,
                    'name':sub_model.name
                }
                sub_qs_list.append(sub_model)
            # 包装字典返回 {市id:xx,市name:xx, subs:[区id1：xx,区name1：xx,区id2：xx,区name2：xx,....]
            data_dict = {
                'id': parent_model.id,
                'name': parent_model.name,
                'subs': sub_qs_list
            }
            cache.set('sub_area' + area_id,data_dict,3600)
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'sub_data':data_dict})